package com.friends.utils.regex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <pre>
 * RegexUtils
 * </pre>
 */
public final class RegexUtils {

    /**
     * 提取标签中间内容
     */
    public static String xmlExtract(String input, String tag) {
        String regex = "<" + Pattern.quote(tag) + ">(.*?)</" + Pattern.quote(tag) + ">";
        Matcher matcher = Pattern.compile(regex).matcher(input);
        return matcher.find() ? matcher.group(1) : "";
    }

    /**
     * 提取标签中间内容（多个相同标签）
     */
    public static List<String> xmlExtractMulti(String input, String tag) {
        List<String> results = new ArrayList<>();
        String regex = "<" + Pattern.quote(tag) + ">(.*?)</" + Pattern.quote(tag) + ">";
        Matcher matcher = Pattern.compile(regex, Pattern.DOTALL).matcher(input);
        while (matcher.find()) {
            results.add(matcher.group(1));
        }
        return results;
    }

    /**
     * 替换标签中间内容
     */
    public static String xmlReplace(String input, String tag, String replacement) {
        String regex = "(<" + Pattern.quote(tag) + ">).*?(" + Pattern.quote("</" + tag + ">") + ")";
        return input.replaceAll(regex, "$1" + replacement + "$2");
    }

    /**
     * 替换标签中间内容（多个相同标签，每个标签替换不同内容）
     */
    public static String xmlReplaceMulti(String input, String tag, List<String> replacements) {
        if (replacements == null || replacements.isEmpty()) {
            return input;
        }

        String regex = "<" + Pattern.quote(tag) + ">(.*?)</" + Pattern.quote(tag) + ">";
        Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(input);
        
        StringBuffer result = new StringBuffer();
        int replacementIndex = 0;
        
        while (matcher.find() && replacementIndex < replacements.size()) {
            String replacement = replacements.get(replacementIndex++);
            matcher.appendReplacement(result, 
                    Matcher.quoteReplacement(matcher.group().replaceFirst(Pattern.quote(matcher.group(1)), replacement)));
        }
        matcher.appendTail(result);
        
        return result.toString();
    }
}
